package org.mozhu.mysql.learning.hitcounter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

@Service("DBSlotHitCounterService")
public class DBSlotHitCounterService implements HitCounterService {
    public static final int SLOT_SIZE = 100;
    @Autowired
    JdbcTemplate jdbcTemplate;

    @Override
    public void increase() {
        // 用数据库的随机数作条件会有并发问题，暂时不清楚是什么原因
//        double round = Math.random();
//         jdbcTemplate.update("UPDATE slot_hit_counter SET cnt = cnt + 1 WHERE slot = CEIL(? * 100) ", round);
//         jdbcTemplate.update("UPDATE slot_hit_counter SET cnt = cnt + 1 WHERE slot = CEIL(RAND() * 100) ");
        int slot = new Random().nextInt(SLOT_SIZE) + 1;
        jdbcTemplate.update("UPDATE slot_hit_counter SET cnt = cnt + 1 WHERE slot = ?", slot);
    }

    @Override
    public int count() {
        return jdbcTemplate.queryForObject("SELECT SUM(cnt) FROM slot_hit_counter", Integer.class);
    }

    @Override
    public void reset() {
        int cnt = jdbcTemplate.update("UPDATE slot_hit_counter SET cnt = 0");
        if (cnt == 0) {
            int slotCount = 100;
            List<Object[]> params = new ArrayList<Object[]>();
            for (int i = 0; i < slotCount; i++) {
                params.add(new Object[]{i + 1});
            }
            jdbcTemplate.batchUpdate("INSERT INTO slot_hit_counter (slot, cnt) values(?,0)", params);
        }
    }
}
